package com.xiaotao.consumer;

import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.client.Channel;
import com.xiaotao.entity.Order;
import com.xiaotao.mapper.OrderMapper;
import com.xiaotao.util.ConstantUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

@Component
@Slf4j
public class CreateOrderConsumer {
    @Resource
    private RedisTemplate redisTemplateInit;

    @Resource
    private OrderMapper orderMapper;

    @RabbitListener(queues = {ConstantUtil.QUEUE_CREATE_ORDER})
    public void consume(String msg, Channel channel, Message message){
        try {
            Order order = JSONObject.parseObject(msg, Order.class);
            //查缓存
            Object o = redisTemplateInit.opsForValue().get(ConstantUtil.REDIS_CREATE_ORDER + order.getOrderNum());
            if (o!=null){
                //不为空说明未生成订单
                orderMapper.addOrder(order);
                //删除缓存
                redisTemplateInit.delete(ConstantUtil.REDIS_CREATE_ORDER + order.getOrderNum());
            }
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            e.printStackTrace();
            try {
                channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,false);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }
    }
}
